#!/bin/bash
set -euo pipefail

repo="openai/codex"
asset_name="codex-x86_64-unknown-linux-gnu.tar.gz"
output_dir="/tmp"
api_url="https://api.github.com/repos/${repo}/releases/latest"

release_json="$(mktemp)"
trap 'rm -f "${release_json}"' EXIT

curl --fail --silent --show-error --location \
  --output "${release_json}" \
  "${api_url}"

tag_name="$(jq -r '.tag_name' "${release_json}")"

if [[ -z "${tag_name}" || "${tag_name}" == "null" ]]; then
  echo "error: could not determine latest release tag" >&2
  exit 1
fi

download_url="$(jq -r --arg name "${asset_name}" '.assets[] | select(.name == $name) | .browser_download_url' "${release_json}")"

if [[ -z "${download_url}" || "${download_url}" == "null" ]]; then
  echo "error: asset ${asset_name} not found in the latest release" >&2
  exit 1
fi

versioned_filename="codex-${tag_name}-x86_64-unknown-linux-gnu.tar.gz"

temp_dir="$(mktemp -d)"
trap 'rm -f "${release_json}"; rm -rf "${temp_dir}"' EXIT

curl --fail --silent --show-error --location \
  --output "${output_dir}/${versioned_filename}" \
  "${download_url}"

tar --extract --gzip --file "${output_dir}/${versioned_filename}" --directory "${temp_dir}"

binary_path="${temp_dir}/codex-x86_64-unknown-linux-gnu"

if [[ ! -f "${binary_path}" ]]; then
  echo "error: expected binary not found after extraction" >&2
  exit 1
fi

install_path="/usr/bin/codex-x86_64-unknown-linux-gnu"

if [[ -e "${install_path}" ]]; then
  rm -f "${install_path}"
fi

mv "${binary_path}" "${install_path}"
chmod 755 "${install_path}"

echo "Installed codex binary from ${versioned_filename} to ${install_path}"
